package org.geekbang.projects.config.source;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
* 文件properties配置  
* @author : KangNing Hu
*/
public class FilePropertiesConfigSource extends AbstractConfigSource{

	public static final FilePropertiesConfigSource INSTANCE  = new FilePropertiesConfigSource();

	private static final String FILE_PATH = "/META-INF/microprofile-config.properties";

	private Map properties = new HashMap<>();

	private ClassLoader classLoader;



	public FilePropertiesConfigSource() {
		super(100, "microprofile config properties");
		loaderFile();
	}

	/**
	 * 加载文件
	 */
	private void loaderFile() {
		this.classLoader = Thread.currentThread().getContextClassLoader();
		try(InputStream resourceAsStream = classLoader.getResourceAsStream(FILE_PATH)) {
			Properties p = new Properties();
			p.load(resourceAsStream);
			this.properties.putAll(p);
		} catch (IOException e) {
			throw new IllegalStateException(e);
		}
	}


	/**
	 * 获取类加载器
	 * @return
	 */
	public ClassLoader getClassLoader() {
		return classLoader;
	}

	@Override
	protected Map<String, String> getSource() throws Throwable {
		return this.properties;
	}
}
